package controller

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"tem/dto/controllerDto"
	"tem/global"
	"tem/middlewares"
	"tem/model"
	"tem/utils"
)

type InstantController struct {
}

func (InstantController) Create(c *gin.Context) {
	//global.DB.AutoMigrate(&model.Instant{})
	var instant model.Instant
	err := middlewares.DefaultValidator(c, &instant)
	fmt.Printf("%#v er", err)
	fmt.Printf("%#v   xxx", instant)
	if err != nil {
		c.JSON(200, gin.H{
			"code": 1,
			"msg":  err.Error(),
		})
	} else {
		model.Instant{}.Create(instant)
		c.JSON(200, gin.H{
			"code": 0,
			"msg":  "发布成功!",
		})
	}
}

func (InstantController) GetAllList(c *gin.Context) {
	global.DB.AutoMigrate(&model.Instant{})
	id, _ := c.GetQuery("userId")
	userId := utils.ToInt(id)
	index, _ := c.GetQuery("pageIndex")
	size, _ := c.GetQuery("pageSize")
	fmt.Println(index, size)
	pageIndex := utils.ToInt(index)
	pageSize := utils.ToInt(size)
	list, count, err := model.Instant{}.GetAllList(userId, pageIndex, pageSize)
	if err != nil {
		c.JSON(200, gin.H{
			"code": 1,
			"msg":  "查询失败",
		})
	} else {
		c.JSON(200, gin.H{
			"code": 0,
			"body": &controllerDto.ResponseInstantList{
				Count: count,
				List:  list,
			},
		})
	}
}

func (InstantController) GetListById(c *gin.Context) {
	var instant model.Instant
	c.ShouldBind(&instant)
	temp, _ := c.Get("id")
	id := temp.(int)
	fmt.Println(instant.ID, "instant.ID")
	data, err := model.Instant{}.GetListById(instant.ID, uint(id))
	if err != nil {
		c.JSON(200, gin.H{
			"code": 1,
			"msg":  "操作失败",
		})
	} else {
		c.JSON(200, gin.H{
			"code": 0,
			"body": data,
		})
	}
}
